package com.qiyun;


import com.serotonin.io.serial.SerialParameters;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.*;

import java.util.Arrays;

/**
 * 通过串口解析MODBUS协议
 * @author cl2
 *
 */
public class ModbusUtil {
    //设定MODBUS网络上从站地址
    private final static int SLAVE_ADDRESS = 1;
    // 串行波特率
    private final static int BAUD_RATE = 9600;

    private ModbusMaster master ;

    public ModbusUtil(String portId,int parity,int dateBits,int stopBit,String portOwnerName,int baudRate) throws ModbusInitException {
        SerialParameters serialParameters = new SerialParameters();
        // 设定MODBUS通讯的串行口
        serialParameters.setCommPortId(portId);
        // 设定成无奇偶校验
        serialParameters.setParity(parity);
        // 设定成数据位是8位
        serialParameters.setDataBits(dateBits);
        // 设定为1个停止位
        serialParameters.setStopBits(stopBit);
        // 设定端口名称
        serialParameters.setPortOwnerName(portOwnerName);
        // 设定端口波特率
        serialParameters.setBaudRate(baudRate);

        // 创建ModbusFactory工厂实例
        ModbusFactory modbusFactory = new ModbusFactory();
        // 创建ModbusMaster实例
        master = modbusFactory.createRtuMaster(serialParameters);
        master.init();
    }

    public void destory(){
        master.destroy();
    }

//    public static void main(String[] args) throws ModbusInitException  {
//        ModbusUtil modbusUtil=new ModbusUtil("COM9",0,8,1,"111",9600);
//
//        modbusUtil.readInputRegistersTest(SLAVE_ADDRESS,10,8);
//
//        modbusUtil.destory();
//
//    }

    /**
     * 读开关量型的输入信号 02
     * @param slaveId 从站地址
     * @param start 起始偏移量
     * @param len 待读的开关量的个数
     */
    public  String  readDiscreteInputTest( int slaveId, int start, int len) {
        String result="";
        try {
            ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(slaveId, start, len);
            ReadDiscreteInputsResponse response = (ReadDiscreteInputsResponse) master.send(request);
            if (response.isException()){
                throw new Exception(response.getExceptionMessage());
//                System.out.println("Exception response: message=" + response.getExceptionMessage());
            }else {
//                System.out.println(Arrays.toString(response.getData()));
                result= Arrays.toString(response.getShortData());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    /**
     * 读保持寄存器上的内容  03
     * @param slaveId 从站地址
     * @param start 起始地址的偏移量
     * @param len 待读寄存器的个数
     */
    public String readHoldingRegistersTest(int slaveId, int start, int len) {
        String result="";
        try {

            ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(
                    slaveId, start, len);
            ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master
                    .send(request);
            if (response.isException()) {
                throw new Exception(response.getExceptionMessage());
            } else {
//                System.out.println(Arrays.toString(response.getShortData()));
//                short[] list = response.getShortData();
//                for(int i = 0; i < list.length; i++){
//                    System.out.print(list[i] + " ");
//                }
                result=Arrays.toString(response.getShortData());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 读输入寄存器上的内容   04
     * @param slaveId 从站地址
     * @param start 起始地址的偏移量
     * @param len 待读寄存器的个数
     */
    public  String readInputRegistersTest(int slaveId, int start, int len) {
        String result="";
        try {
            ReadInputRegistersRequest request = new ReadInputRegistersRequest(slaveId, start, len);
            ReadInputRegistersResponse response = (ReadInputRegistersResponse) master.send(request);

            if (response.isException()){
                throw new Exception(response.getExceptionMessage());
            }else{
//                System.out.println("功能码:4--" + Arrays.toString(response.getShortData()));
                result=Arrays.toString(response.getShortData());
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }



    /**
     * 批量写数据到保持寄存器
     * @param slaveId 从站地址
     * @param start 起始地址的偏移量
     * @param values 待写数据
     */
    public void writeRegistersTest(int slaveId, int start, short[] values) {
        try {
            WriteRegistersRequest request = new WriteRegistersRequest(slaveId, start, values);
            WriteRegistersResponse response = (WriteRegistersResponse) master.send(request);
            if (response.isException()){
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            }
            else {
                System.out.println("Success");
            }
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }
}